import logging
from typing import Dict, List, Any, Optional
from datetime import datetime
from .interface import IExchange, ExchangeType, KLineInterval
from .adapters import GateAdapter

logger = logging.getLogger(__name__)

class ExchangeService:
    """
    交易所服务
    管理多个交易所适配器，提供统一的接口
    """
    
    def __init__(self):
        """初始化交易所服务"""
        self.exchanges: Dict[ExchangeType, IExchange] = {}
    
    def register_exchange(self, exchange: IExchange) -> None:
        """
        注册交易所适配器
        
        参数:
            exchange: 交易所适配器实例
        """
        exchange_type = exchange.get_exchange_type()
        self.exchanges[exchange_type] = exchange
        logger.info(f"已注册交易所: {exchange.get_name()}")
    
    def get_exchange(self, exchange_type: ExchangeType) -> IExchange:
        """
        获取交易所适配器
        
        参数:
            exchange_type: 交易所类型
            
        返回:
            交易所适配器实例
            
        异常:
            ValueError: 如果交易所未注册
        """
        if exchange_type not in self.exchanges:
            raise ValueError(f"交易所未注册: {exchange_type}")
        return self.exchanges[exchange_type]
    
    async def get_klines(
        self, 
        exchange_type: ExchangeType,
        symbol: str, 
        interval: KLineInterval, 
        start_time: Optional[datetime] = None, 
        end_time: Optional[datetime] = None,
        limit: Optional[int] = None
    ) -> List[Dict[str, Any]]:
        """
        获取K线数据
        
        参数:
            exchange_type: 交易所类型
            symbol: 交易对符号
            interval: K线时间间隔
            start_time: 开始时间（可选）
            end_time: 结束时间（可选）
            limit: 返回的K线数量限制（可选）
            
        返回:
            K线数据列表
        """
        exchange = self.get_exchange(exchange_type)
        return await exchange.get_klines(
            symbol=symbol,
            interval=interval,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
    
    async def get_symbols(self, exchange_type: ExchangeType) -> List[str]:
        """
        获取所有可用的交易对符号
        
        参数:
            exchange_type: 交易所类型
            
        返回:
            交易对符号列表
        """
        exchange = self.get_exchange(exchange_type)
        return await exchange.get_symbols()
    
    async def get_ticker(self, exchange_type: ExchangeType, symbol: str) -> Dict[str, Any]:
        """
        获取交易对的最新行情
        
        参数:
            exchange_type: 交易所类型
            symbol: 交易对符号
            
        返回:
            包含最新行情的字典
        """
        exchange = self.get_exchange(exchange_type)
        return await exchange.get_ticker(symbol)
    
    async def close(self):
        """关闭所有交易所适配器"""
        for exchange in self.exchanges.values():
            await exchange.close()
        logger.info("已关闭所有交易所连接")

# 创建交易所服务实例
exchange_service = ExchangeService()

# 注册Gate.io交易所适配器
def register_gate(api_key: str = "", api_secret: str = ""):
    """
    注册Gate.io交易所适配器
    
    参数:
        api_key: API密钥
        api_secret: API密钥秘钥
    """
    gate_adapter = GateAdapter(api_key=api_key, api_secret=api_secret)
    exchange_service.register_exchange(gate_adapter)
    return gate_adapter 